package com.db.log.index;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.List;
import java.util.Set;

import com.db.log.parser.FileParser;
import com.sun.labs.minion.FieldInfo;
import com.sun.labs.minion.FieldInfo.Type;
import com.sun.labs.minion.SearchEngine;
import com.sun.labs.minion.SimpleIndexer;


public class MinionIndexer implements Indexer {

	private SearchEngine searchEngine;
	
	private Set<FileParser> fileParsers;
	

	public void setSearchEngine(SearchEngine searchEngine) {
		this.searchEngine = searchEngine;
	}

	public void setFileParsers(Set<FileParser> fileParsers) {
		this.fileParsers = fileParsers;
	}


	@Override
	public IndexSession createSession() {
		return new MinionIndexSession();
	}
	
	
	private class MinionIndexSession implements IndexSession {

		private SimpleIndexer indexer;
		
		private MinionIndexSession() {
			this.indexer = searchEngine.getSimpleIndexer();
		}
		
		@Override
		public void startDocument(String key) {
			indexer.startDocument(key);
		}

		@Override
		public void addField(String name, String value) {
			addField(name, value, null);
		}
		
		@Override
		public void addField(String name, String value, DateFormat format) {
			Type fieldType = Type.STRING;
			
			FieldInfo fieldInfo = searchEngine.getFieldInfo(name);
			if (fieldInfo != null) {
				fieldType = fieldInfo.getType();
			}
			
			switch (fieldType) {
				case INTEGER:
					indexer.addField(name, Integer.valueOf(value));
					break;
				case FLOAT:
					indexer.addField(name, Double.valueOf(value));
					break;
				case DATE:
					if (format != null) {
						try {
							indexer.addField(name, format.parse(value));
						} 
						catch (ParseException e) {
							e.printStackTrace();
						}
					}
					else {
						indexer.addField(name, value);
					}
					break;
				default:
					indexer.addField(name, value);
			}
			indexer.addField(name, value);
		}

		@Override
		public void endDocument() {
			indexer.endDocument();
		}

		@Override
		public void close() {
			indexer.finish();
		}
		
	}
	
}
